import EventManager from "./common/EventManager";
import GameData from "./common/GameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Node)
    spMain: cc.Node = null;

    @property(cc.Node)
    spPay: cc.Node = null;

    @property(cc.Node)
    spMean: cc.Node = null;

    @property(cc.Node)
    spQueryProducts: cc.Node = null;

    @property(cc.Node)
    spPurchase: cc.Node = null;

    @property(cc.Node)
    spMakeUp: cc.Node = null;

    @property(cc.Node)
    spQueryPurchase: cc.Node = null;

    @property(cc.Label)
    txtContent: cc.Label = null;

    @property(cc.Label)
    txtTitle: cc.Label = null;

    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;


    private intervalTimer;

    start() {
        EventManager.on(EventManager.OUTPUT_CONTENT_CHANGE, this.onChangeTxtContent, this);
        this.spMain.active = true;
        this.spPay.active = false;
        this.txtTitle.string = "主页";
        this.txtContent.string = "";
    }

    /**
     * Click:返回
     */
    onClickBack() {
        if (this.spMean.active) {
            this.txtTitle.string = "主页";
            this.spMain.active = true;
            this.spPay.active = false;
        } else {
            if (!this.spMain.active) {
                this.txtTitle.string = "支付";
                this.spQueryProducts.active = this.spPurchase.active = this.spMakeUp.active = this.spQueryPurchase.active = false;
                this.spMean.active = true;
            }
        }
    }

    /**
     * Click:登录
     */
    onClickLogin() {

        // 第1步:
        this.onChangeTxtContent("\n======>发起初始化init():");
        let res: string = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/init", "");
        this.onChangeTxtContent(">:init " + res);
        if (res.indexOf("Failed") != -1) {
            // 初始化失败-可以做些业务逻辑
            return;
        }

        // 第2步:
        this.onChangeTxtContent("\n======>发起联合登录unionlogin():");
        res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/unionlogin", "");
        this.onChangeTxtContent(">:unionlogin " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 联合登陆失败-可以做些业务逻辑
            return;
        }
        // 处理登录数据
        GameData.onParseData(resObj.data);


        // 第3步
        this.onChangeTxtContent("\n======>发起华为账号登录hwLogin():");
        res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/hwLogin", JSON.stringify(GameData.gamePlayerData)); // 进行华为账号登录
        this.onChangeTxtContent(">:hwLogin " + res);
        resObj = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 华为账号登录-可以做些业务逻辑
            return;
        }
        if (resObj.extraData == "NeedBinding") {
            // 需要进行绑定
            this.onChangeTxtContent("\n======>发起绑定bindPlayer():");
            const param = {
                "thirdOpenId": "111111", // 游戏官方账号
                "teamPlayerId": GameData.gamePlayerData.localPlayer.teamPlayerId
            }
            res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/bindPlayer", JSON.stringify(param));
            this.onChangeTxtContent(">:bindPlayer " + res);
            resObj = JSON.parse(res);
            if (resObj.state == "Failed") {
                // 绑定失败-可以做些业务逻辑
                return;
            }
        }


        // 第4步
        this.onChangeTxtContent("\n======>发起合规校验verifyLocalPlayer():");
        res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/verifyLocalPlayer", GameData.gamePlayerData.boundPlayerInfo.thirdOpenId);
        this.onChangeTxtContent(">:verifyLocalPlayer " + res);
        resObj = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 合规校验-可以做些业务逻辑
            return;
        }
    }

    /**
     * Click:保存玩家角色信息
     */
    onClickRole() {
        // savePlayerRole
        this.onChangeTxtContent("\n======>发起玩家服务-保存玩家角色信息:");
        let param: GSKPlayerRole = {
            roleId: '123',
            roleName: 'Jason',
            serverId: '456',
            serverName: 'Zhangshan',
            gamePlayerId: GameData.gamePlayerData.localPlayer.gamePlayerId,
            teamPlayerId: '000'
        };
        let res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/submitPlayerRole", JSON.stringify(param));
        this.onChangeTxtContent(">:submitPlayerRole " + res);
    }


    /**
     * Click:支付
     */
    onClickPay() {
        this.txtTitle.string = "支付";
        this.spMain.active = false;
        this.spPay.active = this.spMean.active = true;
        this.spQueryProducts.active = this.spPurchase.active = this.spMakeUp.active = this.spQueryPurchase.active = false;
    }

    /**
     * Click:IAPKit初始化
     */
    onClickIAPKitInit() {
        this.onChangeTxtContent("\n======>IAPKit初始化:");
        let res = jsb.reflection.callStaticMethod(true, "entry/src/main/ets/KitMessageHandle", "entry/initIAPKit", "");
        this.onChangeTxtContent(">:initIAPKit " + res);
    }

    /**
     * Click:查询是否支持支付
     */
    onClickQueryPayStatus() {
        this.onChangeTxtContent("\n======>查询是否支持支付:");
        let res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/queryEnv", "");
        this.onChangeTxtContent(">:queryEnv " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 不支持支付
            return;
        }
        GameData.isSupportIAPKit = true;
    }

    /**
     * Click:查询商品信息
     */
    onClickQueryProducts() {
        this.txtTitle.string = "查询商品信息";
        this.spMean.active = false;
        this.spQueryProducts.active = true;

    }

    /**
     * Click:发起购买
     */
    onClickPurchase() {
        this.txtTitle.string = "发起购买";
        this.spMean.active = false;
        this.spPurchase.active = true;

    }

    /**
     * Click:查询购买记录
     */
    onClickOwnedPurchases() {
        this.txtTitle.string = "查询购买记录";
        this.spMean.active = false;
        this.spQueryPurchase.active = true;

    }

    /**
     * Click:补单
     */
    onClickMakeup() {
        this.txtTitle.string = "补单";
        this.spMean.active = false;
        this.spMakeUp.active = true;

    }

    /**
     * Click:查询消耗型商品信息
     */
    onClickQueryProductsInfo(event: cc.Event, type: string) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }

        // 0.查询消耗型商品信息   1.查询非消耗型商品信息  2.查询订阅商品信息
        let productIds = [];
        switch (type) {
            case "0":
                productIds = ["consumeProduct001"];
                this.onChangeTxtContent("\n======>查询消耗型商品信息:");
                break;
            case "1":
                productIds = ["noConsumeProduct001"];
                this.onChangeTxtContent("\n======>查询非消耗型商品信息:");
                break;
            case "2":
                productIds = ["subscribeProduct001"];
                this.onChangeTxtContent("\n======>查询订阅型商品信息:");
                break;
        }
        const param = {
            // 查询的商品必须是您在AppGallery Connect网站配置的商品
            productIds: productIds,
            // productType:
            // iap.ProductType.CONSUMABLE：消耗型商品;0
            // iap.ProductType.NONCONSUMABLE：非消耗型商品;1
            productType: parseInt(type)
        }
        let res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/queryProducts", JSON.stringify(param));
        this.onChangeTxtContent(">:queryProducts " + res);
    }


    /**
     * Click:购买商品
     */
    onClickPurchaseProductsTest(event: cc.Event, type: string) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }

        // 0.购买消耗商品  1.购买非消耗商品  2.购买订阅行商品
        let res: string = "";
        let productId: string = "";
        switch (type) {
            case "0":
                productId = "consumeProduct001";
                this.onChangeTxtContent("\n======>购买消耗商品:");
                break;
            case "1":
                productId = "noConsumeProduct001";
                this.onChangeTxtContent("\n======>购买非消耗商品:");
                break;
            case "2":
                productId = "subscribeProduct001";
                this.onChangeTxtContent("\n======>购买订阅行商品:");
                break;
        }
        const param = {
            // 通过purchase接口购买的商品必须是您在AppGallery Connect网站配置的商品
            productId: productId,
            productType: parseInt(type)
        }
        res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/buy", JSON.stringify(param));
        this.onChangeTxtContent(">:buy " + res);
        let resobj: ResponseParam = JSON.parse(res);
        if (resobj.state == "Success") {
            // 购买成功后，如果有服务端验签，前端到这里就结束了
            // 或把JSON.parse(resobj.data).purchaseData发给服务器进行验签
            // return;


            // 下面演示前端本地验签和完成订单
            this.onLocalSVFinishTest(parseInt(type), [JSON.parse(resobj.data).purchaseData]);
        }
        else if (resobj.extraData) {
            // 购买失败了-查询到可以补单的商品数据
            let resobj2: ResponseParam = JSON.parse(resobj.extraData);
            if (resobj2.state == "Success") {
                let purchaseDataList: string[] = JSON.parse(resobj2.data);
                // 有服务端验签，就把purchaseDataList数据发到服务端进行验签
                // return;


                // 下面演示前端本地验签和完成订单
                this.onLocalSVFinishTest(parseInt(type), purchaseDataList);
            }
        }
    }


    /**
     * Click:补单商品
     */
    onClickMakeupProducts(event: cc.Event, type: string) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }
        switch (type) {
            case "0":
                this.onChangeTxtContent("\n======>补单消耗型商品:");
                break;
            case "1":
                this.onChangeTxtContent("\n======>补单非消耗型商品:");
                break;
            case "2":
                this.onChangeTxtContent("\n======>补单订阅型商品:");
                break;
        }
        // 1.先-查询-有没有需要补单的商品
        let res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/queryPurchase", JSON.stringify([parseInt(type), 1]));
        this.onChangeTxtContent(">:queryPurchase " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Success") {
            let purchaseDataList: string[] = JSON.parse(resObj.data);
            // 有需要补单的订单数据，如果有服务端验签就把数据purchaseDataList发送给服务端
            // return;


            // 下面演示前端本地验签和完成订单
            this.onLocalSVFinishTest(parseInt(type), purchaseDataList);
        }
    }


    /**
     * Click:查询购买记录
     */
    onClickQueryPurchaseProducts(event: cc.Event, type: string) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }
        switch (type) {
            case "0":
                this.onChangeTxtContent("\n======>查询消耗型购买记录:");
                break;
            case "1":
                this.onChangeTxtContent("\n======>查询非消耗型购买记录:");
                break;
            case "2":
                this.onChangeTxtContent("\n======>查询订阅型购买记录:");
                break;
        }
        let res = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/queryPurchase", JSON.stringify([parseInt(type), 0]));
        this.onChangeTxtContent(">:queryPurchase " + res);
    }


    /**
     * 这里是前端进行：验签->完成订单 (演示)
     * @param purchaseDataList 采购数据列表
     */
    onLocalSVFinishTest(productType: number, purchaseDataList: string[]) {
        for (let i = 0; i < purchaseDataList.length; i++) {
            const res: string = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/dealPurchaseData", JSON.stringify([productType, purchaseDataList[i]]));
            this.onChangeTxtContent(">:dealPurchaseData " + purchaseDataList[i] + " | " + res);
            const resObj: ResponseParam = JSON.parse(res);
            // 本地验签成功-进行完成订单
            if (resObj.state == "Success") {
                const res2: string = jsb.reflection.callStaticMethod(false, "entry/src/main/ets/KitMessageHandle", "entry/finishPurchase", resObj.data);
                this.onChangeTxtContent(">:finishPurchase " + purchaseDataList[i] + " | " + res2);
            }
        }
    }


    /**
     * 更改显示内容
     * @param str 内容
     */
    onChangeTxtContent(str: string) {
        this.txtContent.string = this.txtContent.string + str + "\n";

        clearInterval(this.intervalTimer);
        this.intervalTimer = setTimeout(() => {
            let offset = this.scrollview.content.height - this.scrollview.node.height;
            this.scrollview.scrollToOffset(cc.v2(0, offset), 0);
        }, 500);
    }

    /**
    * 测试evalstring
    * @param str 内容
    */
    onTestEvalString(str: string) {
        let res = jsb.reflection.callStaticMethod(true, "entry/src/main/ets/KitMessageHandle", "entry/testEvalString", "游戏调主线程");
    }


    /**
     * 设置弹窗
     */
    onClickSet() {
        cc.resources.load("prefab/setPrefab", cc.Prefab, (err: Error, assets: cc.Prefab) => {
            let prefab = cc.instantiate(assets);
            cc.director.getScene().addChild(prefab);
        });
    }

}

window.test = (a, b) => {
    console.log("和是", (a + b));
}
